package xyz.hzxiao.filter;


import com.alibaba.fastjson2.JSON;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.ExpiredJwtException;
import jakarta.annotation.Resource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;
import xyz.hzxiao.config.IgnorePathProp;
import xyz.hzxiao.result.JsonResult;
import xyz.hzxiao.utils.JwtUtil;
import xyz.hzxiao.utils.PathUtil;

import java.nio.charset.StandardCharsets;
import java.util.Set;

/**
 * @Author: scy
 * @Date: 2022-09-02 17:16
 */
@Component
public class AuthorFilter implements GlobalFilter, Ordered {

    private static final Logger LOG = LoggerFactory.getLogger(AuthorFilter.class);

    @Resource(name = "ignorePathProp")
    private IgnorePathProp pathProp;

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        String url = request.getURI().getPath();
        LOG.info("=====>{}", url);
        //是否为忽略路径
        Set<String> ignorePath = pathProp.getIgnorePath();
        for (String path : ignorePath) {
            if (PathUtil.isPathMatch(url, path)) {
                return chain.filter(exchange);
            }
        }
        return chain.filter(exchange);
//        String sign = request.getHeaders()
//                .getFirst("Authorization");
//        try {
//            Claims claims = JwtUtil.parseJwt(sign, JwtUtil.SIGNING_KEY);
//            String userId = claims.get("userId").toString();
//            ServerHttpRequest.Builder builder = request.mutate();
//            builder.header("userId", userId);
//            return chain.filter(exchange);
//        } catch (ExpiredJwtException jwtException) {
//            LOG.error("sign过期 : {}", sign);
//            return responseError(exchange, "签名过期");
//        } catch (Exception ex) {
//            LOG.error("sign验证失败 : {} ", sign);
//            return responseError(exchange, "签名验证失败");
//        }
    }

    private Mono<Void> responseError(ServerWebExchange exchange, String message) {
        ServerHttpResponse response = exchange.getResponse();
        response.setStatusCode(HttpStatus.UNAUTHORIZED);
        response.getHeaders().setContentType(MediaType.APPLICATION_JSON);
        String errorResult = JSON.toJSONString(JsonResult.fail(HttpStatus.UNAUTHORIZED.value(), message));
        DataBuffer dataBuffer = response.bufferFactory().allocateBuffer(errorResult.length()).write(errorResult.getBytes(StandardCharsets.UTF_8));
        return response.writeWith(Mono.just(dataBuffer));
    }

    @Override
    public int getOrder() {
        return Ordered.HIGHEST_PRECEDENCE;
    }
}
